package com.ww.grtsmanager.Listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ww.grtsmanager.bean.Subject;
import com.ww.grtsmanager.mapper.SubjectMapper;
import com.ww.grtsmanager.vo.ExcelVo;

import java.util.Date;
import java.util.List;

public class ExcelListener extends AnalysisEventListener<ExcelVo> {

    private SubjectMapper subjectMapper;
    private List<Subject>list;
    public ExcelListener(SubjectMapper subjectMapper, List<Subject>list) {

        this.subjectMapper = subjectMapper;
        this.list=list;
    }

    @Override
    public void invoke(ExcelVo excelVo, AnalysisContext analysisContext) {
        Date date = new Date();
        Integer id = subjectMapper.getSubjectByName(excelVo.getOneName());
       if (id == null){
           Subject one = new Subject();
           one.setTitle(excelVo.getOneName());
           one.setParentId(0);
           one.setGmtCreated(date);
           one.setGmtModified(date);
           //执行插入语句之前id值是0
           int i = subjectMapper.addSubject(one);
           if (i == 0){
               throw new RuntimeException("您上传的excel表数据不合法");
           }
           id= one.getId();
       }
       Subject two = new Subject();
       two.setTitle(excelVo.getTwoName());
       two.setParentId(id);
       two.setGmtCreated(date);
       two.setGmtModified(date);
       list.add(two);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    //上传完成以后 读取完成以后执行这个代码 这里批量添加二级类目
        //这样写不合理 目的是为了让我们逻辑清晰 学了mysql事务就行
        int i = subjectMapper.addSubjectList(list);
        if (i==0){
            throw new RuntimeException("插入失败");
        }
    }
}
